<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * MY_Lang
 *
 * @author Simon Emms <simon@simonemms.com>
 * @since 30-Jan-2012
 */
class MY_Lang extends CI_Lang {
    
    
    public $save_name = 'lang';
    
    
    /* Ensure that language is only set once - avoid conflicts */
    protected $_lang_set = false;
    
    
    protected $_arrBegins = array();
    
    
    
    
    
    public function __construct() {
        parent::__construct();
        
        /* Detect the language */
        $objUser = &load_class('User_agent');
        $objConfig = &load_class('Config', 'core');
        $objConfig->load('languages');

        /* Languages available to the user */
        $arrLang = $objConfig->item('languages');
        
        /* Get the browser language */
        $arrBrowser = $objUser->languages();
        
        /* Match the first language set */
        if(is_array($arrBrowser) && count($arrBrowser) > 0) {
            foreach($arrBrowser as $code) {
                if(in_array($code, $arrLang)) {
                    /* Set the language end */
                    $objConfig->set_item('language', $code);
                    break;
                }
            }
        }
    }
    
    
    
    
    
    
    
    
    /**
     * Change Language
     * 
     * Gets the new URL based on the changed
     * language
     * 
     * @param string $lang
     * @param string $url
     * @return string/false
     */
    public function change_language($lang, $url = null) {
        /* Load the CI instance as not in here */
        $objCI = &get_instance();
        
        /* Is it a valid language */
        $arrLang = $objCI->config->item('languages');
        $valid_lang = is_array($arrLang) && in_array($lang, $arrLang);
        
        if($valid_lang) {
            /* Valid language to replace */
            if(is_null($url)) { $url = current_url(); }
            
            /* Remove the domain */
            $site_url = preg_quote(site_url('', false), '/');
            $url = preg_replace('/^('.$site_url.')/i', '', $url);
            
            /* Convert URL to an array */
            $arrUrl = explode('/', $url);
            
            /* What to extract */
            $arrRemove = array(
                $objCI->config->item('language'), /* Current language */
                $objCI->config->item('mobile_flag'), /* Mobile flag */
            );
            
            foreach($arrRemove as $remove) {
                /* Search for the key and check it's in first two parts of URL */
                $id = array_search($remove, $arrUrl);
                
                if($id !== false && $id < 2) {
                    /* Valid key */
                    unset($arrUrl[$id]);
                }
            }
            
            /* Set the language */
            $objCI->config->set_item('language', $lang);
            
            /* Save to cookie/session */
            $this->_save($lang);
            
            /* Compress the string */
            $url = site_url(implode('/', $arrUrl));
            
            return $url;
        }
        
        /* Invalid language */
        return false;
    }
    
    
    
    
    
    
    
    /**
     * Save
     * 
     * Save language to session/cookie
     * 
     * @param string $lang
     */
    protected function _save($lang) {
        /* Load stuff */
        $objCI = &get_instance();
        $objCI->load->library('session');
        
        $objCI->session->setSession($this->save_name, $lang);
        
        $arrCookie = array(
            'name' => $this->save_name,
            'value' => $lang,
            'expire' => 60 * 60 * 24 * 365,
        );
        
        /* Set cookie */
        $objCI->input->set_cookie($arrCookie);
    }
    
    
    
    
    
    
    
    /**
     * Detect Language
     *
     * Detects the language and sets it
     *
     * @param string $code
     * @param int $segment
     */
    public function detect_language($code, $segment) {
        if($this->lang_set() === false && $this->is_lang_code($code)) {

            /* Check it's a valid language */
            $objConfig = &load_class('Config', 'core');
            $objConfig->load('languages');
            $objURI = &load_class('URI', 'core');
            
            $arrLang = $objConfig->item('languages');
            
            if(is_array($arrLang) && in_array($code, $arrLang)) {
                $objConfig->set_item('language', $code);

                /* Mark it as set */
                $this->_lang_set = true;
                
                /* Get rid of language flag */
                unset($objURI->segments[$segment]);
            }

            /* Get rid of the language in the URI */
            $objURI->uri_string = str_replace($code.'/', $objConfig->item('language').'/', $objURI->uri_string);
        }
    }
    
    
    
    
    public function lang_set() { return $this->_lang_set; }
    
    
    
    
    
    /**
     * Begins With
     * 
     * Returns an array of text where the line
     * begins with the given string
     * 
     * @param string $string
     * @return array
     */
    public function begins_with($string = null) {
        if(is_null($string)) {
            return $this->language;
        } elseif(!array_key_exists($string, $this->_arrBegins)) {
            $arrLang = array();
            
            $regex = preg_quote($string, '/');

            if(is_array($this->language) && count($this->language) > 0) {
                foreach($this->language as $line => $text) {
                    if(preg_match('/^'.$regex.'/', $line)) {
                        $arrLang[$line] = $text;
                    }
                }
            }
            
            $this->_arrBegins[$string] = $arrLang;
        }
        
        return $this->_arrBegins[$string];
    }
    
    
    
    
    
    /**
     * Is Lang Code
     *
     * Is the given string in the language code
     * of 'ab' or 'ab-cd'?
     *
     * @param string $code
     * @return bool
     */
    public function is_lang_code($code) { return (bool) preg_match('/^(\w{2}(\-(\w{2}))?)$/', $code); }
    
    
    
    
    
    /**
     * Line
     * 
     * Allows the line to have variables in. Ideally,
     * they should be in the format %n
     * 
     * @param string $line
     * @param array $arrReplace
     * @return string/false
     */
    public function line($line = '', array $arrReplace = array()) {
        /* Get the line */
        $line = parent::line($line);
        
        if($line !== false && count($arrReplace) > 0) {
            /* Check there's something to replace */
            $line = str_replace(array_keys($arrReplace), array_values($arrReplace), $line);
        }
        
        return $line;
    }
    
    
    
}

?>